package cn.daniellee.plugin.ril;

import cn.daniellee.plugin.ril.command.LimiterCommand;
import cn.daniellee.plugin.ril.listener.PlayerListener;
import cn.daniellee.plugin.ril.model.LimitedLore;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class ItemLoreLimiter extends JavaPlugin {

	private static ItemLoreLimiter instance;

	private String prefix;

	private List<LimitedLore> limitedLores = new ArrayList<>();

	public void onEnable(){
		instance = this;

		loadConfig();
		getLogger().info(" ");
		getLogger().info(">>>>>>>>>>>>>>>>>>>>>>>> ItemLoreLimiter Loaded <<<<<<<<<<<<<<<<<<<<<<<<");
		getLogger().info(">>>>> If you encounter any bugs, please contact author's QQ: 768318841 <<<<<");
		getLogger().info(" ");

		Bukkit.getPluginManager().registerEvents(new PlayerListener(), this);
		Bukkit.getPluginCommand("itemlorelimiter").setExecutor(new LimiterCommand());
	}

	public void loadConfig() {
		getLogger().info("[ItemLoreLimiter] Loading config...");
		if(!getDataFolder().exists()) getDataFolder().mkdirs();
		prefix = "&7[&b" + getConfig().get("prompt-prefix", "ItemLoreLimiter") + "&7] &3: &r";
		limitedLores.clear();
		ConfigurationSection limitSection = getConfig().getConfigurationSection("limit-lores");
		if (limitSection != null) {
			Set<String> itemLores = limitSection.getKeys(false);
			for (String itemLore : itemLores) {
				LimitedLore limitedLore = new LimitedLore();
				limitedLore.setItemLore(itemLore);
				limitedLore.setPermission(getConfig().getString("limit-lores." + itemLore + ".permission"));
				this.limitedLores.add(limitedLore);
			}
		}
	}

	@Override
	public void onDisable() {
		getLogger().info(" ");
		getLogger().info(">>>>>>>>>>>>>>>>>>>>>>>> ItemLoreLimiter Unloaded <<<<<<<<<<<<<<<<<<<<<<<<");
		getLogger().info(" ");
	}

	public static ItemLoreLimiter getInstance() {
		return instance;
	}

	public String getPrefix() {
		return prefix;
	}

	public List<LimitedLore> getLimitedLores() {
		return limitedLores;
	}

	public LimitedLore getLimitLoreByItemStack(ItemStack itemStack) {
		ItemMeta itemMeta = itemStack.getItemMeta();
		if (itemMeta != null) {
			List<String> lores = itemMeta.getLore();
			if (lores != null && !lores.isEmpty()) {
				for (String lore : lores) {
					for (LimitedLore limitedLore : this.limitedLores) {
						if (lore.contains(limitedLore.getItemLore()) || lore.contains(limitedLore.getItemLore().replace("&", "§"))) {
							return limitedLore;
						}
					}
				}
			}
		}
		return null;
	}

	public LimitedLore getLimitLoreByLore(String lore) {
		for (LimitedLore limitedLore : this.limitedLores) {
			if (lore.contains(limitedLore.getItemLore()) || lore.contains(limitedLore.getItemLore().replace("&", "§"))) {
				return limitedLore;
			}
		}
		return null;
	}

}